#include <QIODevice>
#include <QFileDialog>
#include <QListView>
#include <QByteArray>
#include <QVariant>
#include <QFileDialog>

#include "mawindow.h"
#include "geometry/KSegPreferencesDialog.h"
#include "geometry/KSegConstruction.h"
#include "geometry/KSegProperties.h"

QString MAWindow::quickPlayDirectory;

MAWindow::MAWindow(KSegDocument *doc )
    : QMainWindow()
{
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    setWindowIcon(QIcon(":/images/calculate.png"));
    if(doc == 0) {
        doc = new KSegDocument();
    }
    else {
        if(doc->getFilename().isEmpty()) setWindowTitle(tr("Math Assistant: Untitled"));
        else
        {
            QFileInfo fileInfo(doc->getFilename());
            setWindowTitle(QString("Math Assistant: ") + fileInfo.fileName());
        }
    }
    quickPlayDirectory = KSegProperties::getProperty("QuickPlayDirectory");

    maxima = new QProcess(this);
    QString program ="./maxima -eval \"(cl-user::run)\" -f --";
    maxima->start(program);

    helpDir = "./doc/html";

    createWidgets(doc);
    createActions();
    createMenus();
    createToolBars();
    createStatusBar();

    completer = new QCompleter(this);
    completer->setModel(modelFromFile(":/maxima.txt"));
    completer->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setWrapAround(false);
    calView->getEditor()->setCompleter(completer);

    setCentralWidget(MAStackedWidget);
    toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(false);
    updateMenus();
    styleChanged(this, "Cleanlooks");

}

MAWindow::~MAWindow()
{

}
QAbstractItemModel *MAWindow::modelFromFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly))
        return new QStringListModel(completer);

#ifndef QT_NO_CURSOR
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#endif
    QStringList words;

    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        if (!line.isEmpty())
            words << line.trimmed();
    }

#ifndef QT_NO_CURSOR
    QApplication::restoreOverrideCursor();
#endif
    return new QStringListModel(words, completer);
}

void MAWindow::createWidgets(KSegDocument *geoDoc)
{
    calView = new CalculatorWidget(this);
    calView->getEditor()->setFocus();
    connect(calView->getEditor(),SIGNAL(sendCommand(QString)),this,SLOT(sendCommand(QString)));
    connect(maxima,SIGNAL(readyReadStandardOutput()),this,SLOT(readResultMaxima()));
    connect(this,SIGNAL(sendResult(QString)),calView->getEditor(),SLOT(getResult(QString)));
    connect(maxima,SIGNAL(finished(int)),this,SLOT(destroyedMaxima()));

    graphView = new PlotWidget;
    connect(graphView->getPlotView(),SIGNAL(status(QString)),this,SLOT(updateStatusBar(QString)));
    geoView = new KSegView(geoDoc);
    connect(geoView,SIGNAL(updateMenus()),this,SLOT(updateMenus()));
    connect(geoView,SIGNAL(statusBarMessage(const QString&)),this,SLOT(updateStatusBar(const QString&)));

    welcomeView = new QTextBrowser(this);
    welcomeView->setSource(QUrl::fromLocalFile(helpDir + "/introduction_use.htm"));

    helpView = new QTextBrowser(this);
    helpView->setSource(QUrl::fromLocalFile(helpDir + "/introduction_intro.htm"));

    helpDocked = new HelpWidget(helpDir,this);
    helpDocked->setMinimumWidth(220);
    addDockWidget(Qt::LeftDockWidgetArea,helpDocked);

    MAStackedWidget = new QStackedWidget(/*this*/);
    MAStackedWidget->addWidget(welcomeView);
    MAStackedWidget->addWidget(calView);
    MAStackedWidget->addWidget(geoView);
    MAStackedWidget->addWidget(graphView);
    MAStackedWidget->addWidget(helpView);
}

void MAWindow::createActions()
{
    //file
    fileNewCalAction = new QAction(tr("Tạo &trang tính mới"),this);
    fileNewCalAction->setIcon(QIcon(":/images/filenewcal.png"));
    connect(fileNewCalAction,SIGNAL(triggered()),this,SLOT(fileNewCalculate()));
    fileNewConsAction = new QAction(tr("Tạo &mẫu mới"),this);
    fileNewConsAction->setIcon(QIcon(":/images/filenewcon.png"));
    connect(fileNewConsAction,SIGNAL(triggered()),this,SLOT(fileNewConstruction()));
    fileNewSketAction = new QAction(tr("Tạo &hình mới"),this);
    fileNewSketAction->setIcon(QIcon(":/images/filenew.png"));
    connect(fileNewSketAction,SIGNAL(triggered()),this,SLOT(fileNewSketch()));
    openAction = new QAction(tr("&Mở"),this);
    openAction->setIcon(QIcon(":/images/fileopen.png"));
    connect(openAction,SIGNAL(triggered()),this,SLOT(fileOpen()));
    saveAction = new QAction(tr("&Lưu"),this);
    saveAction->setIcon(QIcon(":/images/filesave.png"));
    saveAction->setShortcut(tr("Ctrl+S"));
    connect(saveAction,SIGNAL(triggered()),this,SLOT(fileSave()));
    saveAsAction = new QAction(tr("Lưu &với tên khác.."),this);
    saveAsAction->setShortcut(tr("Ctrl+A"));
    saveAsAction->setIcon(QIcon(":/images/filesave.png"));
    connect(saveAsAction,SIGNAL(triggered()),this,SLOT(fileSaveAs()));
    printAction = new QAction(tr("&In..."),this);
    printAction->setShortcut(tr("Ctrl+P"));
    printAction->setIcon(QIcon(":/images/fileprint.png"));
    connect(printAction,SIGNAL(triggered()),this,SLOT(filePrint()));
    fileExportAction = new QAction(tr("&Xuât ra file ảnh"),this);
    fileExportAction->setIcon(QIcon(":/images/fileexport.png"));
    connect(fileExportAction,SIGNAL(triggered()),this,SLOT(fileExportToImage()));

    exitAction = new QAction(tr("T&hoát"),this);
    exitAction->setShortcut(tr("Ctrl+Q"));
    connect(exitAction,SIGNAL(triggered()),this,SLOT(close()));

    //EDIT
    editUndoAct = new QAction(tr("&Hủy thao tác"),this);
    editUndoAct->setShortcut(QKeySequence::Undo);
    connect(editUndoAct,SIGNAL(triggered()),this,SLOT(editUndo()));
    editRedoAct = new QAction(tr("&Làm lại thao tác"),this);
    editRedoAct->setShortcut(QKeySequence::Redo);
    connect(editRedoAct,SIGNAL(triggered()),this,SLOT(editRedo()));
    editDeleteObjectAct = new QAction(tr("&Xóa"),this);
    editDeleteObjectAct->setShortcut(QKeySequence::Delete);
    connect(editDeleteObjectAct,SIGNAL(triggered()),this,SLOT(editDelete()));

    editToggleLabelAct = new QAction(tr("Ẩn/Hiện &tên"),this);
    editToggleLabelAct->setShortcut(tr("Ctrl+L"));
    connect(editToggleLabelAct,SIGNAL(triggered()),this,SLOT(editToggleLabels()));
    editHideLabelAct = new QAction(tr("Ẩ&n tên"),this);
    connect(editHideLabelAct,SIGNAL(triggered()),this,SLOT(editHideLabels()));
    editShowLabelAct = new QAction(tr("H&iển thị tên"),this);
    connect(editShowLabelAct,SIGNAL(triggered()),this,SLOT(editShowLabels()));
    editChangeLabelAct = new QAction(tr("&Đổi tên"),this);
    connect(editChangeLabelAct,SIGNAL(triggered()),this,SLOT(editChangeLabel()));
    editHideObjectAct = new QAction(tr("Ẩn đối tượn&g"),this);
    editHideObjectAct->setShortcut(tr("Ctrl+H"));
    connect(editHideObjectAct,SIGNAL(triggered()),this,SLOT(editHide()));
    editUnhideAllAct = new QAction(tr("Hiển thị &tất cả"),this);
    editUnhideAllAct->setShortcut(tr("Ctrl+U"));
    connect(editUnhideAllAct,SIGNAL(triggered()),this,SLOT(editShowHidden()));

    //edit color menu
    QPixmap temp(32,32);
    editColorBlackAct = new QAction(tr("Đ&en"),this);
    temp.fill(Qt::black);
    editColorBlackAct->setIcon(QIcon(temp));
    editColorBlackAct->setCheckable(true);
    connect(editColorBlackAct,SIGNAL(triggered()),this,SLOT(editColorBlack()));
    editColorGrayAct = new QAction(tr("&Xám"),this);
    temp.fill(Qt::gray);
    editColorGrayAct->setIcon(QIcon(temp));
    editColorGrayAct->setCheckable(true);
    connect(editColorGrayAct,SIGNAL(triggered()),this,SLOT(editColorGray()));
    editColorRedAct = new QAction(tr("&Đỏ"),this);
    temp.fill(Qt::red);
    editColorRedAct->setIcon(QIcon(temp));
    editColorRedAct->setCheckable(true);
    connect(editColorRedAct,SIGNAL(triggered()),this,SLOT(editColorRed()));
    editColorGreenAct = new QAction(tr("X&anh lá"),this);
    temp.fill(Qt::green);
    editColorGreenAct->setIcon(QIcon(temp));
    editColorGreenAct->setCheckable(true);
    connect(editColorGreenAct,SIGNAL(triggered()),this,SLOT(editColorGreen()));
    editColorBlueAct = new QAction(tr("Xanh &da trời"),this);
    temp.fill(Qt::blue);
    editColorBlueAct->setIcon(QIcon(temp));
    editColorBlueAct->setCheckable(true);
    connect(editColorBlueAct,SIGNAL(triggered()),this,SLOT(editColorBlue()));
    editColorYellowAct = new QAction(tr("&Vàng"),this);
    temp.fill(Qt::yellow);
    editColorYellowAct->setIcon(QIcon(temp));
    editColorYellowAct->setCheckable(true);
    connect(editColorYellowAct,SIGNAL(triggered()),this,SLOT(editColorYellow()));
    editColorMagentaAct = new QAction(tr("Đỏ &tươi"),this);
    temp.fill(Qt::magenta);
    editColorMagentaAct->setIcon(QIcon(temp));
    editColorMagentaAct->setCheckable(true);
    connect(editColorMagentaAct,SIGNAL(triggered()),this,SLOT(editColorMagenta()));
    editColorCyanAct = new QAction(tr("Lụ&c lam"),this);
    temp.fill(Qt::cyan);
    editColorCyanAct->setIcon(QIcon(temp));
    editColorCyanAct->setCheckable(true);
    connect(editColorCyanAct,SIGNAL(triggered()),this,SLOT(editColorCyan()));
    editColorOtherAct = new QAction(tr("&Khác..."),this);
    connect(editColorOtherAct,SIGNAL(triggered()),this,SLOT(editColorOther()));
    //edit line style menu
    editLinestyleSolidAct = new QAction(tr("&Liên tục"),this);
    editLinestyleSolidAct->setCheckable(true);
    connect(editLinestyleSolidAct,SIGNAL(triggered()),this,SLOT(editLinestyleSolid()));
    editLinestyleDashedAct = new QAction(tr("&Nét đứt"),this);
    editLinestyleDashedAct->setCheckable(true);
    connect(editLinestyleDashedAct,SIGNAL(triggered()),this,SLOT(editLinestyleDashed()));
    editLinestyleDottedAct = new QAction(tr("&Chấm"),this);
    editLinestyleDottedAct->setCheckable(true);
    connect(editLinestyleDottedAct,SIGNAL(triggered()),this,SLOT(editLinestyleDotted()));
    editLinestyleThinAct = new QAction(tr("&Mỏng"),this);
    editLinestyleThinAct->setCheckable(true);
    connect(editLinestyleThinAct,SIGNAL(triggered()),this,SLOT(editLinestyleThin()));
    editLinestyleNormalAct = new QAction(tr("&Bình thường"),this);
    editLinestyleNormalAct->setCheckable(true);
    connect(editLinestyleNormalAct,SIGNAL(triggered()),this,SLOT(editLinestyleNormal()));
    editLinestyleThickAct = new QAction(tr("Đậ&m"),this);
    editLinestyleThickAct->setCheckable(true);
    connect(editLinestyleThickAct,SIGNAL(triggered()),this,SLOT(editLinestyleThick()));
    //edit point style menu
    editPointStyleLargecircleAct = new QAction(tr("&Lớn"),this);
    editPointStyleLargecircleAct ->setCheckable(true);
    connect(editPointStyleLargecircleAct,SIGNAL(triggered()),this,SLOT(editPointstyleLargecircle()));
    editPointStyleMediumcircleAct = new QAction(tr("&Trung bình"),this);
    editPointStyleMediumcircleAct ->setCheckable(true);
    connect(editPointStyleMediumcircleAct,SIGNAL(triggered()),this,SLOT(editPointstyleMediumcircle()));
    editPointStyleSmallcircleAct = new QAction(tr("&Nhỏ"),this);
    editPointStyleSmallcircleAct ->setCheckable(true);
    connect(editPointStyleSmallcircleAct,SIGNAL(triggered()),this,SLOT(editPointstyleSmallcircle()));
    //edit font
    editFontSize10 = new QAction(tr("10"),this);
    editFontSize10->setCheckable(true);
    connect(editFontSize10,SIGNAL(triggered()),this,SLOT(editFont10()));
    editFontSize14 = new QAction(tr("14"),this);
    editFontSize14->setCheckable(true);
    connect(editFontSize14,SIGNAL(triggered()),this,SLOT(editFont14()));
    editFontSize20 = new QAction(tr("20"),this);
    editFontSize20->setCheckable(true);
    connect(editFontSize20,SIGNAL(triggered()),this,SLOT(editFont20()));
    editFontSize30 = new QAction(tr("30"),this);
    editFontSize30->setCheckable(true);
    connect(editFontSize30,SIGNAL(triggered()),this,SLOT(editFont30()));
    editFontFontAct = new QAction(tr("&Cửa sổ chọn font..."),this);
    connect(editFontFontAct,SIGNAL(triggered()),this,SLOT(editFontFont()));

    editChangeNumberOfSampleAct = new QAction(tr("Tha&y đổi số mẫu..."),this);
    editChangeNumberOfSampleAct->setToolTip(tr("Dùng cho đối tượng quỹ tích"));
    connect(editChangeNumberOfSampleAct,SIGNAL(triggered()),this,SLOT(editChangeNumberOfSamples()));

    editPreferencesAct = new QAction(tr("Tùy &chọn..."),this);
    connect(editPreferencesAct,SIGNAL(triggered()),this,SLOT(editGeoPreferences()));

    editSelectionGroupsAct = new QAction(tr("Chọn th&eo nhóm..."),this);
    connect(editSelectionGroupsAct,SIGNAL(triggered()),this,SLOT(editShowSelectionGroupDialog()));

    //VIEW
    viewPanAct = new QAction(tr("&Di chuyển"),this);
    viewPanAct->setIcon(QIcon(":/images/viewpan.png"));
    connect(viewPanAct,SIGNAL(triggered()),this,SLOT(viewPan()));
    viewZoomAct = new QAction(tr("&Phóng to/Thu nhỏ"),this);
    viewZoomAct->setShortcut(tr("Alt+Z"));
    viewZoomAct->setIcon(QIcon(":/images/viewzoom.png"));
    connect(viewZoomAct,SIGNAL(triggered()),this,SLOT(viewZoom()));
    viewZoomToFitAct = new QAction(tr("P&hóng đầy màn hình"),this);
    viewZoomToFitAct->setIcon(QIcon(":/images/viewfit.png"));
    connect(viewZoomToFitAct,SIGNAL(triggered()),this,SLOT(viewZoomFit()));
    viewOriginalAct = new QAction(tr("Phón&g 100%"),this);
    viewOriginalAct->setIcon(QIcon(":/images/vieworiginal.png"));
    connect(viewOriginalAct,SIGNAL(triggered()),this,SLOT(resetView()));

    grazoominAct = new QAction(tr("&Phóng to"),this);
    grazoominAct->setIcon(QIcon(":/images/grzoomin.png"));
    connect(grazoominAct,SIGNAL(triggered()),graphView->getPlotView(),SLOT(zoomIn()));

    grazoomoutAct = new QAction(tr("&Thu nhỏ"),this);
    grazoomoutAct->setIcon(QIcon(":/images/grzoomout.png"));
    connect(grazoomoutAct,SIGNAL(triggered()),graphView->getPlotView(),SLOT(zoomOut()));
    //NEW
    newIntersectionPoint = new QAction(tr("&Giao điểm"),this);
    newIntersectionPoint->setShortcut(tr("Alt+I"));
    newIntersectionPoint->setIcon(QIcon(":/images/newintersection.png"));
    connect(newIntersectionPoint,SIGNAL(triggered()),SLOT(newGeoIntersectionPoint()));
    newSegment = new QAction(tr("&Đoạn thẳng"),this);
    newSegment->setShortcut(tr("Alt+S"));
    newSegment->setIcon(QIcon(":/images/newsegment.png"));
    connect(newSegment,SIGNAL(triggered()),SLOT(newGeoSegment()));
    newMidpoint = new QAction(tr("&Trung điểm"),this);
    newMidpoint->setShortcut(tr("Alt+M"));
    newMidpoint->setIcon(QIcon(":/images/newmidpoint.png"));
    connect(newMidpoint,SIGNAL(triggered()),SLOT(newGeoMidpoint()));
    newRay = new QAction(tr("T&ia"),this);
    newRay->setShortcut(tr("Alt+R"));
    newRay->setIcon(QIcon(":/images/newray.png"));
    connect(newRay,SIGNAL(triggered()),SLOT(newGeoRay()));
    newLine = new QAction(tr("Đườ&ng thẳng"),this);
    newLine->setShortcut(tr("Alt+L"));
    //newLine->setIcon(QIcon(":/images/newline.png"));
    connect(newLine,SIGNAL(triggered()),SLOT(newGeoLine()));
    newPerpendicularLine = new QAction(tr("Đường &vuông góc"),this);
    newPerpendicularLine->setShortcut(tr("Alt+P"));
    newPerpendicularLine->setIcon(QIcon(":/images/newperpendicularline.png"));
    connect(newPerpendicularLine,SIGNAL(triggered()),SLOT(newGeoPerpendicularLine()));
    newCircleByCenterAndPoint = new QAction(tr("Đường &tròn"),this);
    newCircleByCenterAndPoint->setShortcut(tr("Alt+C"));
    newCircleByCenterAndPoint->setIcon(QIcon(":/images/newcircle.png"));
    connect(newCircleByCenterAndPoint,SIGNAL(triggered()),SLOT(newGeoCircleByCenterAndPoint()));
    newArcByThreePoints = new QAction(tr("&Cung tạo bởi ba điểm"),this);
    newArcByThreePoints->setShortcut(tr("Alt+A"));
    newArcByThreePoints->setIcon(QIcon(":/images/newarcby3points.png"));
    connect(newArcByThreePoints,SIGNAL(triggered()),SLOT(newGeoArcByThreePoints()));
    newAngleBisector = new QAction(tr("Tia &phân giác"),this);
    newAngleBisector->setShortcut(tr("Alt+B"));
    newAngleBisector->setIcon(QIcon(":/images/newanglebisector.png"));
    connect(newAngleBisector,SIGNAL(triggered()),SLOT(newGeoAngleBisector()));
    newLocus = new QAction(tr("&Quỹ tích"),this);
    newLocus->setShortcut(tr("Alt+O"));
    newLocus->setIcon(QIcon(":/images/newlocus.png"));
    connect(newLocus,SIGNAL(triggered()),SLOT(newGeoLocus()));
    newEndpoints = new QAction(tr("Các điểm c&uối"),this);
    newEndpoints->setIcon(QIcon(":/images/newendpoint.png"));
    connect(newEndpoints,SIGNAL(triggered()),SLOT(newGeoEndpoints()));
    newCenterPoint = new QAction(tr("T&âm điểm"),this);
    newCenterPoint->setIcon(QIcon(":/images/newcenterpoint.png"));
    connect(newCenterPoint,SIGNAL(triggered()),SLOT(newGeoCenterPoint()));
    newPolygon = new QAction(tr("&Đa giác"),this);
    newPolygon->setShortcut(tr("Alt+G"));
    newPolygon->setIcon(QIcon(":/images/newpolygon.png"));
    connect(newPolygon,SIGNAL(triggered()),SLOT(newGeoPolygon()));
    newArcSector = new QAction(tr("Hình quạ&t"),this);
    newArcSector->setIcon(QIcon(":/images/newarcsector.png"));
    connect(newArcSector,SIGNAL(triggered()),SLOT(newGeoArcSector()));
    newArcSegment = new QAction(tr("Hình viên &phân"),this);
    newArcSegment->setIcon(QIcon(":/images/newarcsegment.png"));
    connect(newArcSegment,SIGNAL(triggered()),SLOT(newGeoArcSegment()));
    newCircleInterior = new QAction(tr("Hình t&ròn"),this);
    newCircleInterior->setIcon(QIcon(":/images/newcircleinterior.png"));
    connect(newCircleInterior,SIGNAL(triggered()),SLOT(newGeoCircleInterior()));

    //MEASURE
    measureDistance = new QAction(tr("&Khoảng cách"),this);
    measureDistance->setIcon(QIcon(":/images/measuredistance.png"));
    connect(measureDistance,SIGNAL(triggered()),this,SLOT(measureGeoDistance()));
    measureLength = new QAction(tr("Độ &dài"),this);
    measureLength->setIcon(QIcon(":/images/measurelength.png"));
    connect(measureLength,SIGNAL(triggered()),this,SLOT(measureGeoLength()));
    measureRadius = new QAction(tr("Bán &kính"),this);
    measureRadius->setIcon(QIcon(":/images/measureradius.png"));
    connect(measureRadius,SIGNAL(triggered()),this,SLOT(measureGeoRadius()));
    measureAngle = new QAction(tr("&Góc"),this);
    measureAngle->setIcon(QIcon(":/images/measureangle.png"));
    connect(measureAngle,SIGNAL(triggered()),this,SLOT(measureGeoAngle()));
    measureRatio = new QAction(tr("&Tỷ lệ"),this);
    measureRatio->setIcon(QIcon(":/images/measureratio.png"));
    connect(measureRatio,SIGNAL(triggered()),this,SLOT(measureGeoRatio()));
    measureSlope = new QAction(tr("Độ &nghiêng"),this);
    measureSlope->setIcon(QIcon(":/images/measureslope.png"));
    connect(measureSlope,SIGNAL(triggered()),this,SLOT(measureGeoSlope()));
    measureArea = new QAction(tr("&Diện tích"),this);
    measureArea->setIcon(QIcon(":/images/measurearea.png"));
    connect(measureArea,SIGNAL(triggered()),this,SLOT(measureGeoArea()));
    //TRANSFORM
    transformChooseVector = new QAction(tr("Chọn &vector"),this);
    transformChooseVector->setIcon(QIcon(":/images/tranchoosevector.png"));
    connect(transformChooseVector,SIGNAL(triggered()),this,SLOT(transformGeoChooseVector()));
    transformChooseMirror = new QAction(tr("Chọn &trục đối xứng"),this);
    transformChooseMirror->setIcon(QIcon(":/images/tranchoosemirror.png"));
    connect(transformChooseMirror,SIGNAL(triggered()),this,SLOT(transformGeoChooseMirror()));
    transformChooseCenter = new QAction(tr("Chọn tâ&m"),this);
    transformChooseCenter->setIcon(QIcon(":/images/tranchoosecenter.png"));
    connect(transformChooseCenter,SIGNAL(triggered()),this,SLOT(transformGeoChooseCenter()));
    transformChooseAngle = new QAction(tr("Chọn &góc"),this);
    transformChooseAngle->setIcon(QIcon(":/images/tranchooseangle.png"));
    connect(transformChooseAngle,SIGNAL(triggered()),this,SLOT(transformGeoChooseAngle()));
    transformChooseRatio = new QAction(tr("Chọn tỷ &lệ"),this);
    transformChooseRatio->setIcon(QIcon(":/images/tranchooseratio.png"));
    connect(transformChooseRatio,SIGNAL(triggered()),this,SLOT(transformGeoChooseRatio()));
    transformClearChoosen = new QAction(tr("&Bỏ chọn"),this);
    connect(transformClearChoosen,SIGNAL(triggered()),this,SLOT(transformGeoClearChoosen()));
    transformTranslate = new QAction(tr("Phép tịnh &tiến"),this);
    transformTranslate->setIcon(QIcon(":/images/trantranslate.png"));
    connect(transformTranslate,SIGNAL(triggered()),this,SLOT(transformGeoTranslate()));
    transformReflect = new QAction(tr("Phép đối &xứng trục"),this);
    transformReflect->setIcon(QIcon(":/images/tranreflect.png"));
    connect(transformReflect,SIGNAL(triggered()),this,SLOT(transformGeoReflect()));
    transformScale = new QAction(tr("Phép &vị tự"),this);
    transformScale->setIcon(QIcon(":/images/transcale.png"));
    connect(transformScale,SIGNAL(triggered()),this,SLOT(transformGeoScale()));
    transformRotate = new QAction(tr("Phép qua&y"),this);
    transformRotate->setIcon(QIcon(":/images/tranrotate.png"));
    connect(transformRotate,SIGNAL(triggered()),this,SLOT(transformGeoRotate()));

    makeInitial = new QAction(tr("& Khởi tạo ban đầu"),this);
    connect(makeInitial,SIGNAL(triggered()),this,SLOT(initialConstruction()));

    makeGiven = new QAction(tr("Làm đối tượng cho trước"),this);
    connect(makeGiven,SIGNAL(triggered()),this,SLOT(givenConstruction()));

    makeNormal = new QAction(tr("&Hủy chọn đối tượng"),this);
    connect(makeNormal,SIGNAL(triggered()),this,SLOT(normalConstruction()));

    makeFinal = new QAction(tr("& Khởi tạo kết thúc"),this);
    connect(makeFinal,SIGNAL(triggered()),this,SLOT(finalConstruction()));

    recurse = new QAction(tr("Lặp"),this);
    connect(recurse,SIGNAL(triggered()),this,SLOT(recurseConstruction()));

    changeDir = new QAction(tr("&Chọn thư mục mẫu..."),this);
    changeDir->setIcon(QIcon(":/images/changedir.png"));
    connect(changeDir,SIGNAL(triggered()),this,SLOT(quickPlaySetDirectory()));

    geoPlayBox = new QComboBox(this);   
    geoPlayBox->setBaseSize(250,14);
    geoPlayBox->setFixedWidth(150);
    connect(geoPlayBox,SIGNAL(activated(QString)),this,SLOT(quickPlay(QString)));

    maximaAct = new QAction(tr("&Khởi động Maxima"),this);
    maximaAct->setIcon(QIcon(":/images/maxima.png"));
    connect(maximaAct,SIGNAL(triggered()),this,SLOT(restartMaxima()));

    helpAboutAct = new QAction(tr("&Thông tin tác giả"),this);
    connect(helpAboutAct,SIGNAL(triggered()),this,SLOT(about()));
    helpAboutQtAct = new QAction(tr("Thông tin thư viện Qt4.5"),this);
    connect(helpAboutQtAct,SIGNAL(triggered()),qApp,SLOT(aboutQt()));
    helpManualAct = new QAction(tr("&Hướng dẫn"),this);
    connect(helpManualAct,SIGNAL(triggered()),this,SLOT(helpManual()));

    zoominAct = new QAction(QIcon(":/images/zoomin.png"),tr("Phóng to"),this);
    connect(zoominAct,SIGNAL(triggered()),helpView,SLOT(zoomIn()));
    zoomoutAct = new QAction(QIcon(":/images/zoomout.png"),tr("Thu nhỏ"),this);
    connect(zoomoutAct,SIGNAL(triggered()),helpView,SLOT(zoomOut()));
    forwardAct = new QAction(QIcon(":/images/forward.png"),tr("Trang sau"),this);
    connect(forwardAct,SIGNAL(triggered()),helpView,SLOT(forward()));
    backAct = new QAction(QIcon(":/images/back.png"),tr("Trang trước"),this);
    connect(backAct,SIGNAL(triggered()),helpView,SLOT(backward()));
    homeAct = new QAction(QIcon(":/images/home.png"),tr("Trang chủ"),this);
    connect(homeAct,SIGNAL(triggered()),helpView,SLOT(home()));
    connect(helpView,SIGNAL(forwardAvailable(bool)),forwardAct,SLOT(setEnabled(bool)));
    connect(helpView,SIGNAL(backwardAvailable(bool)),backAct,SLOT(setEnabled(bool)));
}
void MAWindow::createToolBars()
{
    mainToolBar = addToolBar(tr("Main ToolBar"));
    addToolBar(Qt::LeftToolBarArea,mainToolBar);
    mainToolBar->setFixedWidth(70);
    mainToolBar->setMovable(false);
    mainToolBar->setIconSize(QSize(70,35));
    for(int i = 0; i < MAXTOOLBUTTON; i++)
    {
        toolButtons[i] = new MAToolButton(this);
        toolButtons[i]->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        mainToolBar->addWidget(toolButtons[i]);
        mainToolBar->addSeparator();
    }
    toolButtons[0]->setIcon(QIcon(":/images/welcome.png"));
    toolButtons[0]->setText(tr("Giới thiệu"));
    toolButtons[0]->setToolTip("Hello!");
    toolButtons[1]->setIcon(QIcon(":/images/calculate.png"));
    toolButtons[1]->setText(tr("Tính toán"));
    toolButtons[2]->setIcon(QIcon(":/images/geometry.png"));
    toolButtons[2]->setText(tr("Hình học"));
    toolButtons[3]->setIcon(QIcon(":/images/graph.png"));
    toolButtons[3]->setText(tr("Đồ thị"));
    toolButtons[4]->setIcon(QIcon(":/images/help.png"));
    toolButtons[4]->setText(tr("Trợ giúp"));

    //Create file toolbar
    fileToolBar = addToolBar(tr("File"));
    fileToolBar->addAction(fileNewCalAction);
    fileToolBar->addAction(fileNewSketAction);
    fileToolBar->addAction(fileNewConsAction);
    fileToolBar->addAction(openAction);
    fileToolBar->addAction(saveAction);
    fileToolBar->addAction(printAction);
    fileToolBar->addAction(maximaAct);
    fileToolBar->addSeparator();
    //Create geometry toolbar
    geoViewToolBar = addToolBar(tr("View"));
    geoViewToolBar->addAction(viewPanAct);
    geoViewToolBar->addAction(viewZoomAct);
    geoViewToolBar->addAction(grazoominAct);
    geoViewToolBar->addAction(grazoomoutAct);
    geoViewToolBar->addAction(viewZoomToFitAct);
    geoViewToolBar->addAction(viewOriginalAct);
    geoViewToolBar->addSeparator();
    geoViewToolBar->addAction(fileExportAction);
    //Create play toolbar
    playToolBar = addToolBar(tr("Play"));
    playToolBar->addWidget(geoPlayBox);
    playToolBar->addAction(changeDir);
    playToolBar->addSeparator();

    geoNewToolBar = addToolBar(tr("New"));
    geoNewToolBar->addAction(newIntersectionPoint);
    geoNewToolBar->addAction(newSegment);
    geoNewToolBar->addAction(newMidpoint);
    geoNewToolBar->addAction(newRay);
    geoNewToolBar->addAction(newLine);
    geoNewToolBar->addAction(newPerpendicularLine);
    geoNewToolBar->addAction(newCircleByCenterAndPoint);
    geoNewToolBar->addAction(newArcByThreePoints);
    geoNewToolBar->addAction(newAngleBisector);
    geoNewToolBar->addAction(newLocus);
    geoNewToolBar->addAction(newEndpoints);
    geoNewToolBar->addAction(newCenterPoint);
    geoNewToolBar->addSeparator();
    geoNewToolBar->addAction(newPolygon);
    geoNewToolBar->addAction(newArcSector);
    geoNewToolBar->addAction(newArcSegment);
    geoNewToolBar->addAction(newCircleInterior);
    geoNewToolBar->addSeparator();

    geoMeasureToolBar = addToolBar(tr("Thướt đo"));
    geoMeasureToolBar->addAction(measureDistance);
    geoMeasureToolBar->addAction(measureLength);
    geoMeasureToolBar->addAction(measureRadius);
    geoMeasureToolBar->addAction(measureAngle);
    geoMeasureToolBar->addAction(measureRatio);
    geoMeasureToolBar->addAction(measureSlope);
    geoMeasureToolBar->addAction(measureArea);
    geoMeasureToolBar->addSeparator();

    geoTransformToolBar = addToolBar(tr("Transform"));
    geoTransformToolBar->addAction(transformChooseVector);
    geoTransformToolBar->addAction(transformChooseMirror);
    geoTransformToolBar->addAction(transformChooseCenter);
    geoTransformToolBar->addAction(transformChooseAngle);
    geoTransformToolBar->addAction(transformChooseRatio);    
    geoTransformToolBar->addSeparator();
    geoTransformToolBar->addAction(transformTranslate);
    geoTransformToolBar->addAction(transformReflect);
    geoTransformToolBar->addAction(transformScale);
    geoTransformToolBar->addAction(transformRotate);
    geoTransformToolBar->addSeparator();

    helpToolBar = addToolBar(tr("Help"));
    helpToolBar->addAction(homeAct);
    helpToolBar->addAction(backAct);
    helpToolBar->addAction(forwardAct);
    helpToolBar->addAction(zoominAct);
    helpToolBar->addAction(zoomoutAct);

    addToolBar(Qt::RightToolBarArea,geoTransformToolBar);
    addToolBar(Qt::RightToolBarArea,geoMeasureToolBar);
    addToolBar(Qt::RightToolBarArea,geoNewToolBar);
    insertToolBarBreak(geoNewToolBar);
}

void MAWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&Hồ sơ"));

    fileNewMenu = fileMenu->addMenu(tr("&Tạo mới"));
    fileNewMenu->addAction(fileNewSketAction);
    fileNewMenu->addAction(fileNewConsAction);
    fileNewMenu->addAction(fileNewCalAction);
    fileMenu->addAction(openAction);
    fileMenu->addAction(saveAction);
    fileMenu->addAction(saveAsAction);
    fileMenu->addSeparator();
    fileMenu->addAction(printAction);
    fileMenu->addAction(fileExportAction);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAction);

    editMenu = menuBar()->addMenu(tr("&Chỉnh sửa"));
    editMenu->addAction(editUndoAct);
    editMenu->addAction(editRedoAct);
    editMenu->addSeparator();
    editMenu->addAction(editDeleteObjectAct);
    editMenu->addSeparator();
    editMenu->addAction(editToggleLabelAct);
    editMenu->addAction(editHideLabelAct);
    editMenu->addAction(editShowLabelAct);
    editMenu->addAction(editChangeLabelAct);
    editMenu->addSeparator();
    editMenu->addAction(editHideObjectAct);
    editMenu->addAction(editUnhideAllAct);
    editMenu->addSeparator();

    editColor = editMenu->addMenu(tr("&Màu"));
    editColor->addAction(editColorBlackAct);
    editColor->addAction(editColorGrayAct);
    editColor->addAction(editColorRedAct);
    editColor->addAction(editColorGreenAct);
    editColor->addAction(editColorBlueAct);
    editColor->addAction(editColorYellowAct);
    editColor->addAction(editColorMagentaAct);    
    editColor->addAction(editColorCyanAct);
    editColor->addSeparator();
    editColor->addAction(editColorOtherAct);

    editLineStyle = editMenu->addMenu(tr("&Kiểu đường"));
    editLineStyle->addAction(editLinestyleSolidAct);
    editLineStyle->addAction(editLinestyleDashedAct);
    editLineStyle->addAction(editLinestyleDottedAct);
    editLineStyle->addSeparator();
    editLineStyle->addAction(editLinestyleThinAct);
    editLineStyle->addAction(editLinestyleNormalAct);
    editLineStyle->addAction(editLinestyleThickAct);

    editPointStyle = editMenu->addMenu(tr("K&iểu điểm"));
    editPointStyle->addAction(editPointStyleLargecircleAct);
    editPointStyle->addAction(editPointStyleMediumcircleAct);
    editPointStyle->addAction(editPointStyleSmallcircleAct);

    editFontMenu = editMenu->addMenu(tr("&Font"));
    editFontMenu->addAction(editFontSize10);
    editFontMenu->addAction(editFontSize14);
    editFontMenu->addAction(editFontSize20);
    editFontMenu->addAction(editFontSize30);
    editFontMenu->addSeparator();
    editFontMenu->addAction(editFontFontAct);

    editMenu->addSeparator();
    editMenu->addAction(editChangeNumberOfSampleAct);
    editMenu->addSeparator();
    editMenu->addAction(editPreferencesAct);
    editMenu->addSeparator();
    editMenu->addAction(editSelectionGroupsAct);
    editMenu->addSeparator();

    viewMenu = menuBar()->addMenu(tr("&Hiển thị"));
    viewMenu->addAction(viewPanAct);
    viewMenu->addAction(viewZoomAct);
    viewMenu->addAction(viewZoomToFitAct);
    viewMenu->addAction(viewOriginalAct);
    viewMenu->addSeparator();

    newMenu = menuBar()->addMenu(tr("&Tạo mới"));
    newMenu->addAction(newIntersectionPoint);
    newMenu->addAction(newSegment);
    newMenu->addAction(newMidpoint);
    newMenu->addAction(newRay);
    newMenu->addAction(newLine);
    newMenu->addAction(newPerpendicularLine);
    newMenu->addAction(newCircleByCenterAndPoint);
    newMenu->addAction(newArcByThreePoints);
    newMenu->addAction(newAngleBisector);
    newMenu->addAction(newLocus);
    newMenu->addAction(newEndpoints);
    newMenu->addAction(newCenterPoint);
    newMenu->addSeparator();
    newMenu->addAction(newPolygon);
    newMenu->addAction(newArcSector);
    newMenu->addAction(newArcSegment);
    newMenu->addAction(newCircleInterior);
    newMenu->addSeparator();

    measureMenu = menuBar()->addMenu(tr("&Đo đạc"));
    measureMenu->addAction(measureDistance);
    measureMenu->addAction(measureLength);
    measureMenu->addAction(measureRadius);
    measureMenu->addAction(measureAngle);
    measureMenu->addAction(measureRatio);
    measureMenu->addAction(measureSlope);
    measureMenu->addAction(measureArea);
    measureMenu->addSeparator();

    transformMenu = menuBar()->addMenu(tr("&Phép biến hình"));
    transformMenu->addAction(transformChooseVector);
    transformMenu->addAction(transformChooseMirror);
    transformMenu->addAction(transformChooseCenter);
    transformMenu->addAction(transformChooseAngle);
    transformMenu->addAction(transformChooseRatio);
    transformMenu->addAction(transformClearChoosen);
    transformMenu->addSeparator();
    transformMenu->addAction(transformTranslate);
    transformMenu->addAction(transformReflect);
    transformMenu->addAction(transformScale);
    transformMenu->addAction(transformRotate);
    transformMenu->addSeparator();

    construction = menuBar()->addMenu(tr("Tạo &mẫu"));
    construction->addAction(makeGiven);
    construction->addAction(makeNormal);
    construction->addAction(makeFinal);
    construction->addAction(makeInitial);
    construction->addSeparator();
    construction->addAction(recurse);

    playMenu = menuBar()->addMenu(tr("P&lay"));
    playMenu->addAction(changeDir);
    graphMenu = menuBar()->addMenu(tr("&Graph"));
    graphMenu->addAction(grazoominAct);
    graphMenu->addAction(grazoomoutAct);
    graphMenu->addAction(viewOriginalAct);


    maximaMenu = menuBar()->addMenu(tr("M&axima"));
    maximaMenu->addAction(maximaAct);

    helpMenu = menuBar()->addMenu(tr("&Trợ giúp"));
    helpMenu->addAction(helpAboutAct);
    helpMenu->addAction(helpAboutQtAct);
    helpMenu->addAction(helpManualAct);
    helpMenu->addSeparator();
}

void MAWindow::changeStackedWidget(MAToolButton* ma)
{
    for(int i = 0; i < MAXTOOLBUTTON; ++i)
    {
        if(ma == toolButtons[i])
        {
            MAStackedWidget->setCurrentIndex(i);
            toolButtons[i]->setAutoRaise(false);
        }
        else
        {
            toolButtons[i]->setAutoRaise(true);
        }
    }
    updateMenus();
}
void MAWindow::createStatusBar()
{
    statusBar()->showMessage(tr("Sẵn sàng"));

}
void MAWindow::closeEvent(QCloseEvent *ev)
{
    if(exitProgram())
    {
        maxima->terminate();
        ev->accept();
    }
    else ev->ignore();
}
bool MAWindow::openFile(QString fileName,MAWindow *win)
{
    if(QFileInfo(fileName).exists() == false) {
        QMessageBox::warning(0, tr("Không tìm thấy file"),
                           tr("Tập tin %1 không tồn tại.").arg(fileName),
                           QMessageBox::Ok, 0);
        return false;
    }

    QFile f(fileName);

    bool isConstruction;

  //check to make sure the file won't crash us.
    if(f.open(QIODevice::ReadOnly)) {
        char block[4];

        f.read(block, 4);

        if(block[0] || block[1] || block[2] || block[3] + 5 > (int)f.size()) {
            QMessageBox::warning(0, tr("Invalid file"),
                           tr("Tập tin %1 không giống định dạng file .sec").arg(fileName),
                           QMessageBox::Ok, 0);
            f.close();
            return false;
        }


        f.ungetChar(block[3]);
        f.ungetChar(block[2]);
        f.ungetChar(block[1]);
        f.ungetChar(block[0]);


        QDataStream stream(&f);
        stream.setVersion(QDataStream::Qt_4_5);

        QString tmp;

        stream >> tmp;

        if(!KSegDocument::parseVersionString(tmp, &isConstruction)) {
            QMessageBox::warning(0, tr("Invalid file"),
                           tr("Tập tin %1 không giống định dạng file .seg").arg(fileName),
                           QMessageBox::Ok, 0);
            f.close();
            return false;
        }
        f.close();
    }

    if(f.open(QIODevice::ReadOnly)) {
        QDataStream stream(&f);
        stream.setVersion(QDataStream::Qt_4_5);

        if(isConstruction) {
            if(win == NULL) win = new MAWindow(new KSegConstruction());
            else win->changeDocument(new KSegConstruction());

        }
        else {
            if(win == NULL) win = new MAWindow();
            else win->changeDocument(new KSegDocument());

        }

        stream >> *(win->geoView->getDocument());
        f.close();
    }

    win->geoView->getDocument()->emitDocumentSaved(fileName);
    win->geoView->redrawBuffer();
    win->MAStackedWidget->setCurrentIndex(2);

    return true;
}

void MAWindow::fileNewCalculate()
{
    maxima->close();
    QString program ="./maxima -eval \"(cl-user::run)\" -f --";
    maxima->start(program);
    if(MAStackedWidget->currentIndex() == 1)
        calView->fileNew();
    toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(true);
    toolButtons[1]->setAutoRaise(false);
    MAStackedWidget->setCurrentIndex(1);
    updateMenus();
}

void MAWindow::fileNewSketch()
{
    if(!closingGeoDoc()) return;
    changeDocument(new KSegDocument());
    toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(true);
    toolButtons[2]->setAutoRaise(false);
    MAStackedWidget->setCurrentIndex(2);
    updateMenus();
}

void MAWindow::fileNewConstruction()
{
    if(!closingGeoDoc()) return;
    changeDocument(new KSegConstruction());
    toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(true);
    toolButtons[2]->setAutoRaise(false);
    MAStackedWidget->setCurrentIndex(2);
    updateMenus();
}

void MAWindow::changeDocument(KSegDocument *doc)
{
    QWidget * wg = MAStackedWidget->widget(2);
    MAStackedWidget->removeWidget(wg);
    QSize size = this->size();
    delete wg;
    if(doc->getFilename().isEmpty())
    {
        setWindowTitle(tr("Math Assistant: Untitled"));
    }
    else
    {
        QFile file(doc->getFilename());
        QFileInfo fileInfo(file);
        setWindowTitle(QString("Math Assistant: ") + fileInfo.fileName());
    }

    if(doc->isConstruction() == false) {
        geoView = new KSegView(doc, this);
        MAStackedWidget->insertWidget(2,geoView);
    }
    else {
        QSplitter *sp = new QSplitter(this);
        geoView = new KSegView(doc, sp);
        sp->setOrientation(Qt::Horizontal);
        sp->setOpaqueResize(true);
        MAStackedWidget->insertWidget(2,sp);
    }
    resize(size);
    connect(geoView, SIGNAL(statusBarMessage(const QString &)), this, SLOT(updateStatusBar(const QString &)));
    connect(geoView, SIGNAL(updateMenus()), this, SLOT(updateMenus()));
}

void MAWindow::updateMenus()
{
    QString lineStr;
    QString pathLineIcon;
    if((MAStackedWidget->currentIndex()) == 2)
    {
        G_refs x = geoView->getDocument()->getSelected();
        int i;
        for(i = 0; i < (int)x.count(); i++)
        {
            if(x.at(i)->getType() & G_STRAIGHT)
                break;
        }
        if(i == (int)x.count())
        {
            pathLineIcon = (":/images/newline.png");
            if(x.count() > 2)
                lineStr = tr("&Các đường thẳng");
            else
                lineStr = tr("&Đường thẳng");
        }
        else {
            pathLineIcon = (":/images/newparline.png");
            if(x.count() > 2)
                lineStr = tr("Các đường thẳng song song");
            else
                lineStr = tr("Đường thẳng song song");
        }
    }
    //update edit menu
    editUndoAct->setEnabled(geoView->getDocument()->canEditUndo());
    editRedoAct->setEnabled(geoView->getDocument()->canEditRedo());
    editDeleteObjectAct->setEnabled(geoView->getDocument()->canEditDelete());
    editToggleLabelAct->setEnabled(geoView->getDocument()->canEditToggleLabels());
    editHideLabelAct->setEnabled(geoView->getDocument()->canEditHide());
    editShowLabelAct->setEnabled(geoView->getDocument()->canEditToggleLabels());
    editChangeLabelAct->setEnabled(geoView->getDocument()->canEditChangeLabel());
    editHideObjectAct->setEnabled(geoView->getDocument()->canEditHide());
    editUnhideAllAct->setEnabled(geoView->getDocument()->canEditShowHidden());
    editChangeNumberOfSampleAct->setEnabled(geoView->getDocument()->canEditChangeNumberOfSamples());
    editPreferencesAct->setEnabled(false);
    editSelectionGroupsAct->setEnabled(false);

    grazoominAct->setVisible(false);
    grazoomoutAct->setVisible(false);
    viewOriginalAct->setVisible(false);
    viewPanAct->setVisible(false);
    viewZoomAct->setVisible(false);
    viewZoomToFitAct->setVisible(false);

    fileNewConsAction->setVisible(false);
    fileNewSketAction->setVisible(false);
    fileNewCalAction->setVisible(false);

    maximaMenu->menuAction()->setVisible(false);;
    maximaAct->setVisible(false);
    construction->menuAction()->setVisible(false);
    editMenu->setEnabled(true);
    fileExportAction->setEnabled(false);
    saveAction->setEnabled(false);
    saveAsAction->setEnabled(false);
    printAction->setEnabled(false);

    helpToolBar->hide();
    helpDocked->hide();
    graphMenu->menuAction()->setVisible(false);
    switch((MAStackedWidget->currentIndex()))
    {
    case 0://welcome
        viewMenu->menuAction()->setVisible(false);
        newMenu->menuAction()->setVisible(false);
        measureMenu->menuAction()->setVisible(false);
        transformMenu->menuAction()->setVisible(false);
        playMenu->menuAction()->setVisible(false);
        geoNewToolBar->hide();
        geoMeasureToolBar->hide();
        geoTransformToolBar->hide();
        playToolBar->hide();
        geoViewToolBar->hide();

        fileNewConsAction->setVisible(true);
        fileNewSketAction->setVisible(true);
        fileNewCalAction->setVisible(true);
        fileToolBar->show();
        break;
    case 1://calculate
        editMenu->setEnabled(false);
        printAction->setEnabled(true);
        saveAction->setEnabled(true);
        saveAsAction->setEnabled(true);
        viewMenu->menuAction()->setVisible(false);
        newMenu->menuAction()->setVisible(false);
        measureMenu->menuAction()->setVisible(false);
        transformMenu->menuAction()->setVisible(false);
        playMenu->menuAction()->setVisible(false);
        geoNewToolBar->hide();
        geoMeasureToolBar->hide();
        geoTransformToolBar->hide();
        playToolBar->hide();
        geoViewToolBar->hide();

        fileNewCalAction->setVisible(true);
        fileToolBar->show();
        maximaMenu->menuAction()->setVisible(true);
        maximaAct->setVisible(true);
        maximaAct->setEnabled(maxima->state() != 2);
        break;
    case 2://geometry
        printAction->setEnabled(true);
        saveAction->setEnabled(true);
        saveAsAction->setEnabled(true);
        fileExportAction->setEnabled(true);
        fileNewConsAction->setVisible(true);
        fileNewSketAction->setVisible(true);
        fileToolBar->show();

        playToolBar->show();
        geoViewToolBar->show();
        viewOriginalAct->setVisible(true);
        viewPanAct->setVisible(true);
        viewZoomAct->setVisible(true);
        viewZoomToFitAct->setVisible(true);
        fileNewConsAction->setVisible(true);
        updatePlayBox();
        editPreferencesAct->setEnabled(true);
        editSelectionGroupsAct->setEnabled(true);
        //set visible
        if(geoView->getDocument()->isConstruction())
        {
            construction->menuAction()->setVisible(true);
            makeFinal->setEnabled(geoView->getDocument()->canConstructionMakeFinal());
            makeGiven->setEnabled(geoView->getDocument()->canConstructionMakeGiven());
            makeInitial->setEnabled(geoView->getDocument()->canConstructionMakeInitial());
            makeNormal->setEnabled(geoView->getDocument()->canConstructionMakeNormal());
            recurse->setEnabled(geoView->getDocument()->canConstructionRecurse());
        }
        else
        construction->menuAction()->setVisible(false);
        viewMenu->menuAction()->setVisible(true);
        newMenu->menuAction()->setVisible(true);
        measureMenu->menuAction()->setVisible(true);
        transformMenu->menuAction()->setVisible(true);
        playMenu->menuAction()->setVisible(true);
        geoNewToolBar->show();
        geoMeasureToolBar->show();
        geoTransformToolBar->show();
        //update new menu
        newIntersectionPoint->setEnabled(geoView->getDocument()->canNewIntersection());
        newSegment->setEnabled(geoView->getDocument()->canNewSegment());
        newMidpoint->setEnabled(geoView->getDocument()->canNewMidpoint());
        newRay->setEnabled(geoView->getDocument()->canNewRay());

        newLine->setText(lineStr);
        newLine->setIcon(QIcon(pathLineIcon));
        newLine->setEnabled(geoView->getDocument()->canNewLine());

        newPerpendicularLine->setEnabled(geoView->getDocument()->canNewPerpendicular());
        newCircleByCenterAndPoint->setEnabled(geoView->getDocument()->canNewCircle());
        newArcByThreePoints->setEnabled(geoView->getDocument()->canNewArc());
        newAngleBisector->setEnabled(geoView->getDocument()->canNewBisector());
        newLocus->setEnabled(geoView->getDocument()->canNewLocus());
        newEndpoints->setEnabled(geoView->getDocument()->canNewEndpoints());
        newCenterPoint->setEnabled(geoView->getDocument()->canNewCenterpoint());
        newPolygon->setEnabled(geoView->getDocument()->canNewPolygon());
        newArcSector->setEnabled(geoView->getDocument()->canNewArcSector());
        newArcSegment->setEnabled(geoView->getDocument()->canNewArcSegment());
        newCircleInterior->setEnabled(geoView->getDocument()->canNewCircleInterior());
        //update measure menu
        measureDistance->setEnabled(geoView->getDocument()->canMeasureDistance());
        measureLength->setEnabled(geoView->getDocument()->canMeasureLength());
        measureRadius->setEnabled(geoView->getDocument()->canMeasureRadius());
        measureAngle->setEnabled(geoView->getDocument()->canMeasureAngle());
        measureRatio->setEnabled(geoView->getDocument()->canMeasureRatio());
        measureSlope->setEnabled(geoView->getDocument()->canMeasureSlope());
        measureArea->setEnabled(geoView->getDocument()->canMeasureArea());
        //measureCalculate->setEnabled(geoView->getDocument()->canMeasureCalculate());
        //update transform
        transformChooseVector->setEnabled(geoView->getDocument()->canTransformChooseVector());
        transformChooseMirror->setEnabled(geoView->getDocument()->canTransformChooseMirror());
        transformChooseCenter->setEnabled(geoView->getDocument()->canTransformChooseCenter());
        transformChooseAngle->setEnabled(geoView->getDocument()->canTransformChooseAngle());
        transformChooseRatio->setEnabled(geoView->getDocument()->canTransformChooseRatio());
        transformClearChoosen->setEnabled(geoView->getDocument()->canTransformClearChosen());
        transformTranslate->setEnabled(geoView->getDocument()->canTransformTranslate());
        transformReflect->setEnabled(geoView->getDocument()->canTransformReflect());
        transformScale->setEnabled(geoView->getDocument()->canTransformScale());
        transformRotate->setEnabled(geoView->getDocument()->canTransformRotate());
        break;
    case 3://graph
        graphMenu->menuAction()->setVisible(true);
        fileExportAction->setEnabled(true);
        editMenu->setEnabled(false);
        viewMenu->menuAction()->setVisible(false);
        newMenu->menuAction()->setVisible(false);
        measureMenu->menuAction()->setVisible(false);
        transformMenu->menuAction()->setVisible(false);
        playMenu->menuAction()->setVisible(false);
        geoNewToolBar->hide();
        geoMeasureToolBar->hide();
        geoTransformToolBar->hide();
        playToolBar->hide();
        geoViewToolBar->show();
        fileToolBar->hide();
        grazoominAct->setVisible(true);
        grazoomoutAct->setVisible(true);
        viewOriginalAct->setVisible(true);
        break;
    case 4://help
        viewMenu->menuAction()->setVisible(false);
        newMenu->menuAction()->setVisible(false);
        measureMenu->menuAction()->setVisible(false);
        transformMenu->menuAction()->setVisible(false);
        playMenu->menuAction()->setVisible(false);
        geoNewToolBar->hide();
        geoMeasureToolBar->hide();
        geoTransformToolBar->hide();
        playToolBar->hide();
        geoViewToolBar->hide();
        helpToolBar->show();
        helpDocked->show();
        fileToolBar->hide();
        break;
    }    

    if(geoView->getDocument()->canEditChangeColor())
    {
        editColor->menuAction()->setEnabled(true);
        editColorBlackAct->setChecked(false);
        editColorGrayAct->setChecked(false);
        editColorRedAct->setChecked(false);
        editColorGreenAct->setChecked(false);
        editColorBlueAct->setChecked(false);
        editColorYellowAct->setChecked(false);
        editColorMagentaAct->setChecked(false);
        editColorCyanAct->setChecked(false);
        QColor colorTemp = geoView->getDocument()->getCurrentColor();
        if(colorTemp ==  Qt::black)
             editColorBlackAct->setChecked(true);
        if(colorTemp == Qt::gray)
            editColorGrayAct->setChecked(true);
        if(colorTemp == Qt::red)
            editColorRedAct->setChecked(true);
        if(colorTemp ==Qt::green)
            editColorGreenAct->setChecked(true);
        if(colorTemp == Qt::blue)
            editColorBlueAct->setChecked(true);
        if(colorTemp == Qt::yellow)
            editColorYellowAct->setChecked(true);
        if(colorTemp == Qt::magenta)
            editColorMagentaAct->setChecked(true);
        if(colorTemp == Qt::cyan)
            editColorCyanAct->setChecked(true);
    }
    else
        editColor->menuAction()->setEnabled(false);

    if(geoView->getDocument()->canEditChangeLinestyle())
    {
        editLineStyle->menuAction()->setEnabled(true);
        editLinestyleSolidAct->setChecked(false);
        editLinestyleDashedAct->setChecked(false);
        editLinestyleDottedAct->setChecked(false);        
        Qt::PenStyle styleTemp = geoView->getDocument()->getCurrentPenstyle();
        if(styleTemp == Qt::SolidLine)
            editLinestyleSolidAct->setChecked(true);
        if(styleTemp == Qt::DashLine)
            editLinestyleDashedAct->setChecked(true);
        if(styleTemp == Qt::DotLine)
            editLinestyleDottedAct->setChecked(true);

        editLinestyleThinAct->setChecked(false);
        editLinestyleNormalAct->setChecked(false);
        editLinestyleThickAct->setChecked(false);
        switch(geoView->getDocument()->getCurrentPenWidth())
        {
        case 0:
            editLinestyleThinAct->setChecked(true);
            break;
        case 2:
            editLinestyleNormalAct->setChecked(true);
            break;
        case 3:
            editLinestyleThickAct->setChecked(true);
            break;
        }
    }
    else
        editLineStyle->menuAction()->setEnabled(false);

    if(geoView->getDocument()->canEditChangePointstyle())
    {
        editPointStyle->menuAction()->setEnabled(true);
        editPointStyleLargecircleAct->setChecked(false);
        editPointStyleMediumcircleAct->setChecked(false);
        editPointStyleSmallcircleAct->setChecked(false);
        switch(geoView->getDocument()->getCurrentPointstyle())
        {
        case LARGE_CIRCLE:
            editPointStyleLargecircleAct->setChecked(true);
            break;
        case MEDIUM_CIRCLE:
            editPointStyleMediumcircleAct->setChecked(true);
            break;
        case SMALL_CIRCLE:
            editPointStyleSmallcircleAct->setChecked(true);
            break;
        case ANY:
            break;
        }
    }
    else
        editPointStyle->menuAction()->setEnabled(false);

    if(geoView->getDocument()->canEditChangeFont())
    {
        editFontMenu->menuAction()->setEnabled(true);
        editFontSize10->setChecked(false);
        editFontSize14->setChecked(false);
        editFontSize20->setChecked(false);
        editFontSize30->setChecked(false);
        switch(geoView->getDocument()->getCurrentFontsize())
        {
        case 10:
            editFontSize10->setChecked(true);
            break;
        case 14:
            editFontSize14->setChecked(true);
            break;
        case 20:
            editFontSize20->setChecked(true);
            break;
        case 30:
            editFontSize30->setChecked(true);
            break;
        }
    }
    else
        editFontMenu->menuAction()->setEnabled(false);    
}

void MAWindow::fileSaveAs()
{
    switch(MAStackedWidget->currentIndex())
    {
        case 1:
        {
            calView->fileSaveAs();
            break;
        }
        case 2:
        {
            QString fileName;

            if(geoView->getDocument()->isConstruction()) {
                fileName = QFileDialog::getSaveFileName(this,tr("Save File As"),
                                                geoView->getDocument()->getFilename(),"*.sec");

                if(fileName.isNull()) return;

                if(!QFileInfo(fileName).fileName().contains('.'))
                    fileName = fileName + ".sec";
            }
            else {
                fileName = QFileDialog::getSaveFileName(this,tr("Save File As"),
                                                geoView->getDocument()->getFilename(),"*.seg");

                if(fileName.isNull()) return;

                if(!QFileInfo(fileName).fileName().contains('.'))
                    fileName = fileName + ".seg";
            }

            QFile f(fileName);

            if(f.open(QIODevice::WriteOnly)) {
                QDataStream stream(&f);
                stream.setVersion(QDataStream::Qt_4_5);

                stream << *(geoView->getDocument());
                f.close();
            }
            geoView->getDocument()->emitDocumentSaved(fileName);
            break;
        }
    }
}

void MAWindow::fileSave()
{
    switch(MAStackedWidget->currentIndex())
    {
        case 1:
        {
            calView->fileSave();
            break;
        }
        case 2:
        {
            if(geoView->getDocument()->getFilename().isEmpty()) {
                fileSaveAs();
                return;
            }

            QString fileName = geoView->getDocument()->getFilename();
            QFile f(fileName);

            if(f.open(QIODevice::WriteOnly)) {
                QDataStream stream(&f);
                stream.setVersion(QDataStream::Qt_4_5);

                stream << *(geoView->getDocument());
                f.close();
            }

            geoView->getDocument()->emitDocumentSaved(fileName);
            break;
        }
    }
}
void MAWindow::fileOpen()
{
    QString fileName = QFileDialog::getOpenFileName(0,0,QString::null, "*.seg *.sec *.cal");
    toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(true);
    if(fileName.endsWith(".cal", Qt::CaseInsensitive))
    {
        calView->fileOpen(fileName);
        MAStackedWidget->setCurrentIndex(1);
        toolButtons[1]->setAutoRaise(false);
    }
    if(fileName.endsWith(".seg", Qt::CaseInsensitive) || fileName.endsWith(".sec", Qt::CaseInsensitive))
    {
        if(!closingGeoDoc()) return;
        if(openFile(fileName,this))
        {
            KSegProperties::setProperty("RecentFile1", fileName);
            MAStackedWidget->setCurrentIndex(2);
            toolButtons[2]->setAutoRaise(false);
        }
    }
    toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(false);
    updateMenus();

}

void MAWindow::filePrint()
{
    switch(MAStackedWidget->currentIndex())
    {
        case 1:
        {
            calPrint();
            break;
        }
        case 2:
        {
            geoPrint();
            break;
        }
    }
}

void MAWindow::geoPrint()
{
    QPrinter *pr = geoView->getDocument()->getPrinter();
    QPrintDialog dialog(pr,this);
    if(dialog.exec()) {
        pr->setFullPage(false);
        QPainter p(pr);
        QRect viewPort = p.viewport();
        QRect docSize(0, 0, geoView->width() - KSegView::ScrollBarThickness,
                      geoView->height() - KSegView::ScrollBarThickness);
        QRect vp = docSize;
        int dpix = pr->logicalDpiX();
        int dpiy = pr->logicalDpiY();
        vp.setWidth((vp.width() * dpix) / 96); //96 DPI looks good in my tests
        vp.setHeight((vp.height() * dpiy) / 96);
        QPoint offs = viewPort.center() - vp.center();
        vp.translate(offs.x(), offs.y());
        p.setViewport(vp);
        p.setWindow(docSize);
        p.setClipRect(p.combinedTransform().mapRect(docSize));
        geoView->getDocument()->print(p, ViewTransform(geoView->getOffsetX(), geoView->getOffsetY(), geoView->getZoom()));
    }
}

void MAWindow::calPrint()
{
    QPrinter printer(QPrinter::HighResolution);
    QPrintDialog *dlg = new QPrintDialog(&printer, this);
    if (calView->getEditor()->textCursor().hasSelection())
        dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection);
    dlg->setWindowTitle(tr("Print Document"));
    if (dlg->exec() == QDialog::Accepted) {
        calView->getEditor()->print(&printer);
    }
    delete dlg;
}

void MAWindow::graphPrint()
{

}

void MAWindow::fileExportToImage()
{
    switch(MAStackedWidget->currentIndex())
    {
    case 2:
        geoExportToImage();
        break;
    case 3:
        graphView->exportToImage();
        break;
    }
}

void MAWindow::geoExportToImage()
{
    QDialog dial(this,Qt::Window);
    QVBoxLayout layout(&dial);

    dial.setWindowTitle(tr("E&xport To Image...").replace(QRegExp("&"), ""));
    QLabel lab(tr("Chọn định dạng ảnh:"), &dial);
    QListWidget format(&dial);
    QList<QByteArray> liststr=QImageWriter::supportedImageFormats ();
    for(int i=0; i < liststr.size();i++)
    {
        format.insertItem(-1,QString(liststr.at(i)));
    }
    QCheckBox hiq(tr("High Quality Image"), &dial);
    QPushButton okBut(tr("OK"), &dial);
    connect(&okBut, SIGNAL(clicked()), &dial, SLOT(accept()));
    okBut.setDefault(true);

    layout.setMargin(10);
    layout.setSpacing(5);
    layout.addWidget(&lab);
    layout.addWidget(&format);
    layout.addSpacing(15);
    layout.addWidget(&hiq);
    layout.addSpacing(15);
    layout.addWidget(&okBut, 0, Qt::AlignHCenter);

    QList<QListWidgetItem*> pngItem = format.findItems("png",0);
    if(pngItem.count()>0)
    {
        format.setCurrentItem(pngItem.at(0));
    }

    dial.exec();

    if(dial.result() == QDialog::Rejected) return;

    QString fmt = format.currentItem()->text();
    QString ext = fmt.toLower();
    if(ext == "jpeg") ext = "jpg";
    QString fileName = QFileDialog::getSaveFileName(0,tr("Xuất ra ảnh...").replace(QRegExp("&"), ""),
                                                   QString::null,"*." + ext);

    if(fileName.isNull()) return;

    QRect area = geoView->rect();
    area.setWidth(area.width() - KSegView::ScrollBarThickness);
    area.setHeight(area.height() - KSegView::ScrollBarThickness);

    if(hiq.isChecked()) {
        setCursor(QCursor(Qt::WaitCursor));
        repaint();
        statusBar()->showMessage(tr("Đang xuất ảnh, vui lòng đợi..."));

        int qX = (area.width() + 3) / 4, qY = (area.height() + 3) / 4;
        QPixmap pmap(4 * (qX + 3), 4 * (qY + 3));

        QImage outImg(QPixmap(4 * qX, 4 * qY).toImage());

        for(int x = 0; x < 4; ++x) for(int y = 0; y < 4; ++y) {
            pmap.fill(QColor(KSegProperties::getProperty("BackgroundColor")));

            QPainter p(&pmap);

            int offsX = x * qX;
            int offsY = y * qY;

            p.setWindow(QRect(offsX - 1, offsY - 1, qX + 3, qY + 3));

            geoView->getDocument()->print(p, ViewTransform(geoView->getOffsetX(), geoView->getOffsetY(),
                                                           geoView->getZoom()));

            QImage img(pmap.toImage());

            img = img.scaled(qX + 3, qY + 3);

            for(int x2 = 0; x2 < qX; ++x2) for(int y2 = 0; y2 < qY; ++y2) {
                outImg.setPixel(offsX + x2, offsY + y2, img.pixel(x2 + 1, y2 + 1));
            }
        }
        outImg.save(fileName, fmt.toAscii());
        setCursor(QCursor(Qt::ArrowCursor));
    }
    else {
        QPixmap pmap(area.width(), area.height());

        pmap.fill(QColor(KSegProperties::getProperty("BackgroundColor")));

        QPainter p(&pmap);

        geoView->getDocument()->print(p, ViewTransform(geoView->getOffsetX(), geoView->getOffsetY(),
                                                       geoView->getZoom()));

        pmap.save(fileName, fmt.toAscii());
    }
}

void MAWindow::fileChooseLanguage()
{
}

bool MAWindow::closingGeoDoc()
{
    if(geoView->getDocument()->isModified() == false)
    {
        geoView->delDocumentRef();
        return true;
    }

    int ans = QMessageBox::warning(this, tr("Save?"),
                                   tr("Bạn có muốn lưu những thay đổi?"),
                                   QMessageBox::Yes, QMessageBox::No,
                                   QMessageBox::Cancel);
    if(ans == QMessageBox::Cancel) {
        return false;
    }
    if(ans == QMessageBox::Yes)
    {
        fileSave();
        if(geoView->getDocument()->isModified() == true) { //check if the guy hit cancel
        return false;
        }
    }
    geoView->delDocumentRef();
    return true;
}

void MAWindow::editGeoPreferences()
{
    KSegPreferencesDialog p(this, true);
    p.exec();
}

//new menu
void MAWindow::newGeoSegment()
{
   geoView->getDocument()->newSegment();
}

void MAWindow::newGeoIntersectionPoint()
{
    geoView->getDocument()->newIntersection();
}

void MAWindow::newGeoMidpoint()
{
    geoView->getDocument()->newMidpoint();
}

void MAWindow::newGeoRay()
{
    geoView->getDocument()->newRay();
}

void MAWindow::newGeoLine()
{
    geoView->getDocument()->newLine();
}

void MAWindow::newGeoPerpendicularLine()
{
    geoView->getDocument()->newPerpendicular();
}

void MAWindow::newGeoCircleByCenterAndPoint()
{
    geoView->getDocument()->newCircle();
}

void MAWindow::newGeoArcByThreePoints()
{
    geoView->getDocument()->newArc();
}

void MAWindow::newGeoAngleBisector()
{
    geoView->getDocument()->newBisector();
}

void MAWindow::newGeoLocus()
{
    geoView->getDocument()->newLocus();
}

void MAWindow::newGeoEndpoints()
{
    geoView->getDocument()->newEndpoints();
}

void MAWindow::newGeoCenterPoint()
{
    geoView->getDocument()->newCenterpoint();
}

void MAWindow::newGeoPolygon()
{
    geoView->getDocument()->newPolygon();
}

void MAWindow::newGeoArcSector()
{
    geoView->getDocument()->newArcSector();
}

void MAWindow::newGeoArcSegment()
{
    geoView->getDocument()->newArcSegment();
}

void MAWindow::newGeoCircleInterior()
{
    geoView->getDocument()->newCircleInterior();
}

//measure menu
void MAWindow::measureGeoDistance()
{
    geoView->getDocument()->measureDistance();
}

void MAWindow::measureGeoLength()
{
    geoView->getDocument()->measureLength();
}

void MAWindow::measureGeoRadius()
{
    geoView->getDocument()->measureRadius();
}

void MAWindow::measureGeoAngle()
{
    geoView->getDocument()->measureAngle();
}

void MAWindow::measureGeoRatio()
{
    geoView->getDocument()->measureRatio();
}

void MAWindow::measureGeoSlope()
{
    geoView->getDocument()->measureSlope();
}

void MAWindow::measureGeoArea()
{
    geoView->getDocument()->measureArea();
}

//transform menu

void MAWindow::transformGeoChooseVector()
{
    geoView->getDocument()->transformChooseVector();
}

void MAWindow::transformGeoChooseMirror()
{
    geoView->getDocument()->transformChooseMirror();
}

void MAWindow::transformGeoChooseCenter()
{
    geoView->getDocument()->transformChooseCenter();
}

void MAWindow::transformGeoChooseAngle()
{
    geoView->getDocument()->transformChooseAngle();
}

void MAWindow::transformGeoChooseRatio()
{
    geoView->getDocument()->transformChooseRatio();
}

void MAWindow::transformGeoClearChoosen()
{
    geoView->getDocument()->transformClearChosen();
}

void MAWindow::transformGeoTranslate()
{
    geoView->getDocument()->transformTranslate();
}

void MAWindow::transformGeoReflect()
{
    geoView->getDocument()->transformReflect();
}

void MAWindow::transformGeoScale()
{
    geoView->getDocument()->transformScale();
}

void MAWindow::transformGeoRotate()
{
    geoView->getDocument()->transformRotate();
}

void MAWindow::quickPlay(QString fileName)
{
    int which = -1;
    vector<QString> files = getValidConstructionFiles();

    for(unsigned int i = 0; i < files.size(); i++)
    {
        if(QFileInfo(files[i]).fileName() == fileName)
        {
            which = i;
            break;
        }
    }

    QFile f(files[which]);
    KSegConstruction temp;

    if(f.open(QIODevice::ReadOnly)) {
        QDataStream stream(&f);
        stream.setVersion(QDataStream::Qt_4_5);
        stream >> temp;
        f.close();
    }
    vector<KSegConstruction *> cs = KSegConstruction::getAllConstructions();

    int c = (int)cs.size();

    while(c--) {
        if(cs[c] == &temp) break;
    }

    Q_ASSERT(c != -1);

    geoView->playConstruction(c);

}
void MAWindow::quickPlaySetDirectory()
{
    QFileDialog fd(0,0,quickPlayDirectory, "*.sec");
    fd.setFileMode(QFileDialog::Directory);

    if(fd.exec() != QDialog::Accepted) return;
    QStringList strList = fd.selectedFiles();
    QString newDir;
    if(strList.count()>0)
        newDir = fd.selectedFiles().at(0);
    if(newDir.isNull()) return;

    quickPlayDirectory = newDir;
    KSegProperties::setProperty("QuickPlayDirectory", newDir);
}
void MAWindow::editUndo()
{
    geoView->getDocument()->editUndo();
}
void MAWindow::editRedo()
{
    geoView->getDocument()->editRedo();
}
void MAWindow::editDelete()
{
    geoView->getDocument()->editDelete();
}
void MAWindow::editToggleLabels()
{
    geoView->getDocument()->editToggleLabels();
}
void MAWindow::editHideLabels()
{
    geoView->getDocument()->editHideLabels();
}
void MAWindow::editShowLabels()
{
    geoView->getDocument()->editShowLabels();
}
void MAWindow::editChangeLabel()
{
    geoView->getDocument()->editChangeLabel();
}
void MAWindow::editHide()
{
    geoView->getDocument()->editHide();
}
void MAWindow::editShowHidden()
{
    geoView->getDocument()->editShowHidden();
}
void MAWindow::editChangeNumberOfSamples()
{
    geoView->getDocument()->editChangeNumberOfSamples();
}
void MAWindow::editShowSelectionGroupDialog()
{
    geoView->getDocument()->editShowSelectionGroupDialog();
}

void MAWindow::editColorBlack()
{
  geoView->getDocument()->setCurrentColor(Qt::black);
  updateMenus();
}

void MAWindow::editColorGray()
{
  geoView->getDocument()->setCurrentColor(Qt::gray);
  updateMenus();
}

void MAWindow::editColorRed()
{
  geoView->getDocument()->setCurrentColor(Qt::red);
  updateMenus();
}

void MAWindow::editColorGreen()
{
  geoView->getDocument()->setCurrentColor(Qt::green);
  updateMenus();
}

void MAWindow::editColorBlue()
{
  geoView->getDocument()->setCurrentColor(Qt::blue);
  updateMenus();
}

void MAWindow::editColorYellow()
{
  geoView->getDocument()->setCurrentColor(Qt::yellow);
  updateMenus();
}

void MAWindow::editColorMagenta()
{
  geoView->getDocument()->setCurrentColor(Qt::magenta);
  updateMenus();
}

void MAWindow::editColorCyan()
{
  geoView->getDocument()->setCurrentColor(Qt::cyan);
  updateMenus();
}

void MAWindow::editColorOther()
{
  QColor newColor;

  newColor = QColorDialog::getColor(geoView->getDocument()->getCurrentColor());

  if(newColor.isValid()) {
    geoView->getDocument()->setCurrentColor(newColor);
  }
  updateMenus();
}
//----------

void MAWindow::editPointstyleLargecircle()
{
  geoView->getDocument()->setCurrentPointstyle(LARGE_CIRCLE);
  updateMenus();
}


void MAWindow::editPointstyleMediumcircle()
{
  geoView->getDocument()->setCurrentPointstyle(MEDIUM_CIRCLE);
  updateMenus();
}


void MAWindow::editPointstyleSmallcircle()
{
  geoView->getDocument()->setCurrentPointstyle(SMALL_CIRCLE);
  updateMenus();
}

//---------

void MAWindow::editLinestyleSolid()
{
  geoView->getDocument()->setCurrentPenstyle(Qt::SolidLine);
  updateMenus();
}


void MAWindow::editLinestyleDashed()
{
  geoView->getDocument()->setCurrentPenstyle(Qt::DashLine);
  updateMenus();
}


void MAWindow::editLinestyleDotted()
{
  geoView->getDocument()->setCurrentPenstyle(Qt::DotLine);  
  updateMenus();
}


void MAWindow::editLinestyleThin()
{
  geoView->getDocument()->setCurrentPenWidth(0);
  updateMenus();
}


void MAWindow::editLinestyleNormal()
{
  geoView->getDocument()->setCurrentPenWidth(2);
  updateMenus();
}


void MAWindow::editLinestyleThick()
{
  geoView->getDocument()->setCurrentPenWidth(3);
  updateMenus();
}

//---------

void MAWindow::editFont10()
{
  geoView->getDocument()->setCurrentFontsize(10);
  updateMenus();
}
void MAWindow::editFont14()
{
  geoView->getDocument()->setCurrentFontsize(14);
  updateMenus();
}
void MAWindow::editFont20()
{
  geoView->getDocument()->setCurrentFontsize(20);
  updateMenus();
}
void MAWindow::editFont30()
{
  geoView->getDocument()->setCurrentFontsize(30);
  updateMenus();
}

void MAWindow::editFontFont()
{
  bool ok;
  QFont f = QFontDialog::getFont(&ok, geoView->getDocument()->getCurrentFont());
  if(ok) {
    geoView->getDocument()->setCurrentFont(f);
  }
  updateMenus();
}

void MAWindow::initialConstruction()
{
    geoView->getDocument()->constructionMakeInitial();
}

void MAWindow::finalConstruction()
{
    geoView->getDocument()->constructionMakeFinal();
}

void MAWindow::givenConstruction()
{
    geoView->getDocument()->constructionMakeGiven();
}

void MAWindow::normalConstruction()
{
   geoView->getDocument()->constructionMakeNormal();
}

void MAWindow::recurseConstruction()
{
    geoView->getDocument()->constructionRecurse();
}

void MAWindow::sendCommand(QString command)
{
    QByteArray byteCommand(command.toAscii());
    byteCommand.append('\n');
    if(maxima->state()!=2)
    {
        emit sendResult(tr("Maxima is not running. Please start Maxima"));
        return;
    }
    maxima->write(byteCommand);
}
void MAWindow::readResultMaxima()
{

    QString result(maxima->readAll());

    emit sendResult(result);
}
static void setStyleHelper(QWidget *widget, QStyle *style)
{
    widget->setStyle(style);
    widget->setPalette(style->standardPalette());
    foreach (QObject *child, widget->children()) {
        if (QWidget *childWidget = qobject_cast<QWidget *>(child))
            setStyleHelper(childWidget, style);
    }
}
void MAWindow::styleChanged(QWidget *widget, const QString &styleName)
{
    QStyle *style = QStyleFactory::create(styleName);
    if (style)
        setStyleHelper(widget, style);
}


vector<QString> MAWindow::getValidConstructionFiles()
{
  vector<QString> toBeReturned;

  QDir myDir = QDir(quickPlayDirectory);
  QStringList filters;
  filters << "*.sec";
  myDir.setNameFilters(filters);
  myDir.setSorting(QDir::Name);
  myDir.setFilter(QDir::Files | QDir::Readable);

  QStringList entries = myDir.entryList();

  int i;
  for(i = 0; i < (int)entries.count(); ++i) {
    QString entry = entries[i];

    toBeReturned.push_back(myDir.absolutePath() + "/" + entry);
  }
  return toBeReturned;
}

void MAWindow::updatePlayBox()
{
    geoPlayBox->clear();

    vector<QString> files = this->getValidConstructionFiles();

    int i;
    for(i = 0; i < (int)files.size(); ++i) {
      QFile f(files[i]);
      ScanType s = KSegConstruction::scanConstructionFile(f, geoView->getDocument()->getSelected());
      if(s == INVALID || s != MATCHED) continue;
      geoPlayBox->addItem(QFileInfo(files[i]).fileName());
    }
}

void MAWindow::viewPan()
{
    geoView->viewPan();
}

void MAWindow::viewZoom()
{
    geoView->viewZoom();
}

void MAWindow::viewZoomFit()
{
    geoView->viewZoomFit();
}

void MAWindow::resetView()
{
    switch(MAStackedWidget->currentIndex())
    {
        case 2:
            geoView->viewOrigZoom();
        break;
        case 3:
            graphView->getPlotView()->resetViewport();
        break;
    }
}

void MAWindow::restartMaxima()
{
    if(maxima->state()!=2)
    {
        QString program ="./maxima -eval \"(cl-user::run)\" -f --";
        maxima->start(program);
        maximaAct->setEnabled(false);
    }
    else
        QMessageBox::about(0,tr("Maxima"),tr("Maxima đang chạy"));
}

void MAWindow::updateStatusBar(const QString& s)
{
    this->statusBar()->showMessage(s);
}

void MAWindow::help()
{
    toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(false);
}

bool MAWindow::exitProgram()
{
    if(geoView->getDocument()->isModified() == false && calView->getEditor()->document()->isModified() == false) {
        geoView->delDocumentRef();
        calView->getEditor()->clear();
        return true;
    }
    bool ans1 = true, ans2 = true;
    if(geoView->getDocument()->isModified() == true)
    {
        toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(true);
        MAStackedWidget->setCurrentIndex(2);
        toolButtons[2]->setAutoRaise(false);
        int ans = QMessageBox::warning(this, tr("Save?"),
                                 tr("Bạn có muốn lưu những thay đổi tập tin hình học không?"),
                                 QMessageBox::Yes, QMessageBox::No,
                                 QMessageBox::Cancel);
        if(ans == QMessageBox::Cancel)
        {
            ans1 = false;
        }
        else if(ans == QMessageBox::Yes)
        {
            fileSave();
            if(geoView->getDocument()->isModified() == true)
                return false;
        }
    }

    if(calView->getEditor()->document()->isModified() == true)
    {
        toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(true);
        MAStackedWidget->setCurrentIndex(1);
        toolButtons[1]->setAutoRaise(false);
        int ans = QMessageBox::warning(this, tr("Save?"),
                                 tr("Bạn có muốn lưu những thay đổi tập tin tính toán không?"),
                                 QMessageBox::Yes, QMessageBox::No,
                                 QMessageBox::Cancel);
        if(ans == QMessageBox::Cancel)
        {
            ans2 = false;
        }
        else if(ans == QMessageBox::Yes)
        {
            fileSave();
            if(calView->getEditor()->document()->isModified() == true)
                return false;
        }
    }
    if(!ans1 || !ans2)
        return false;
    geoView->delDocumentRef();
    return true;
}

void MAWindow::activateHelpModule(QListWidgetItem* item)
{
    QString name_and_section(item->text());
    QRegExp modname_pattern("^\\s*(\\b\\w+\\b)\\s*\\((\\b\\w+\\b)\\)");
    if (modname_pattern.indexIn(name_and_section) < 0)
        return;
    helpView->setSource(QUrl::fromLocalFile(helpDir+"/"+modname_pattern.cap(2) + "_" + modname_pattern.cap(1)+".htm"));
}

void MAWindow::activateHelpModule(QTreeWidgetItem* item, int)
{
    QString fulltext(item->text(0));
    QRegExp modname("^\\s*(\\b[\\w]+\\b)");
    if (modname.indexIn(fulltext) < 0)
        return;
    QString module(modname.cap(1).toLower());
    helpView->setSource(QUrl::fromLocalFile(helpDir+"/"+item->text(1)+"_"+module+".htm"));
}
void MAWindow::helpText(QString fulltext)
{
    QList<QListWidgetItem *> items = helpDocked->m_flist->findItems(fulltext.toLower(),Qt::MatchStartsWith);
    if (items.isEmpty()) {
        QMessageBox::warning(this, "helpwin",
                   "Không thể tìm tập tin trợ giúp cho '" + fulltext + "'\n",
                   QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton);
        return;
    }
    QListWidgetItem* item = items.at(0);
    QString name_and_section(item->text());
    QRegExp modname_pattern("^\\s*(\\b\\w+\\b)\\s*\\((\\b\\w+\\b)\\)");
    if (modname_pattern.indexIn(name_and_section) < 0)
        return;
    helpView->setSource(QUrl::fromLocalFile(helpDir+"/"+modname_pattern.cap(2) + "_" + modname_pattern.cap(1)+".html"));
}
void MAWindow::destroyedMaxima()
{
    maximaAct->setEnabled(true);
}

void MAWindow::helpManual()
{
    toolButtons[MAStackedWidget->currentIndex()]->setAutoRaise(true);
    MAStackedWidget->setCurrentIndex(4);
    toolButtons[4]->setAutoRaise(false);
    updateMenus();
}
void MAWindow::about()
{
    QString text;
    text += "Math Assistant Version ";
    text += VERSION;
    text += "\n\n";
    text += "Web: http://sites.google.com/site/mathvnsoft\n";
    text += "Email: mathassistant2009@gmail.com\n";
    text += "Email: huynhlamlinh1985a@yahoo.com\n";
    text += "Email: lephukhanhhuy@yahoo.com\n";
    QMessageBox::about(this, tr("Tác giả"), text);
}
